﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyContainerParameter : Parameter {
		/// <summary>
		/// 
		/// </summary>
		public string Property { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) {
			if (control == null)
				return null;

			if (string.IsNullOrWhiteSpace(Property))
				return null;

			var ct = control;
			while (ct != null) {
				if (ct is UserControl) {
					var prop = ct.GetType().GetProperty(Property);
					if (prop != null)
						return prop.GetValue(ct, null);
				} else if (ct is Page) {
					var prop = ct.GetType().GetProperty(Property);
					if (prop != null)
						return prop.GetValue(ct, null);
					else
						throw new NullReferenceException(
							string.Format("Cannot find property: \"{0}.{1}\".", ct.GetType(), Property));
				}

				ct = ct.Parent;
			}

			return null;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected override System.Web.UI.WebControls.Parameter Clone() {
			var ret = new MyContainerParameter();
			ret.Name = Name;
			ret.Size = Size;
			ret.Type = Type;
			ret.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
			ret.DbType = DbType;
			ret.DefaultValue = DefaultValue;
			ret.Direction = Direction;
			ret.Property = Property;

			return ret;
		}
	} // end of MyControlParameter.
}
